package com.aaa.springboot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aaa.springboot.commons.exception.MyException;
import com.aaa.springboot.commons.lang.Result;
import com.aaa.springboot.dao.PermissionDao;
import com.aaa.springboot.dao.TUserDao;
import com.aaa.springboot.pojo.Permission;
import com.aaa.springboot.pojo.TUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private TUserDao tUserDao;

    // 连接数据库
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (StrUtil.isBlank(username)) {
            log.info("登录用户：{} 不存在", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        // 根据用户名查询用户ID
        TUser tUser = tUserDao.selectByUsernameTUser(username);
        if (StringUtils.isEmpty(tUser.getPassword()) || StringUtils.isEmpty(tUser.getUsername())) {
            log.info("查询未返回用户结果'" + username + "'");
            throw new UsernameNotFoundException("用户名或密码错误");
        }


        List<SimpleGrantedAuthority> authorities = new ArrayList<>();


        List<Permission> permissions = permissionDao.selectAll(tUser.getId());

        //permissions.forEach(permission -> {
        //    Map<String, String> privileges = permission.getPrivileges();
        //    privileges.forEach((key,value)->{
        //        // 拼接  %s-%s 就是  后边的第一和个参数和第二个参数用-进行分割
        //        authorities.add(new SimpleGrantedAuthority(String.format("%s-%s", permission.getId(), value)));
        //    });
        //});
        //


        User user = new User(tUser.getUsername(), tUser.getPassword(), authorities(permissions));
        return user;
    }

    private Collection<? extends GrantedAuthority> authorities(List<Permission> permissions) {
        List<GrantedAuthority> list = new ArrayList<>();
        permissions.forEach(permission -> {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getCode());
            list.add(authority);
        });

        return list;


    }
}
